package com.thinkgem.jeesite.modules.mobile.service;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.modules.source.entity.program.EleSourceProgram;
import com.thinkgem.jeesite.modules.source.service.program.EleSourceProgramService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhangchong zhangc@passiontec.cn
 * @since 2018/1/7 18:56
 */
@RestController
@RequestMapping(value = "${adminPath}/mobile")
public class AppDownloadInterFaceService{

    private EleSourceProgramService eleSourceProgramService;

    @Autowired
    public AppDownloadInterFaceService(EleSourceProgramService eleSourceProgramService){
        this.eleSourceProgramService = eleSourceProgramService;
    }

    /**
     * app软件下载,1显示程序，2设置程序，3MCU程序
     */
    @RequestMapping("download")
    public Result index(String appType,String remarks, HttpServletRequest request){
        List<EleSourceProgram> applications = eleSourceProgramService.findNewVersionApp(appType,remarks);
        if(!CollectionUtils.isEmpty(applications)){
            for(EleSourceProgram application:applications){
                String basePath = DictUtils.getDictValue("basePath", "systemvalue", "");
                if(StringUtils.isEmpty(basePath)){
                    String requestURL = request.getRequestURL().toString();
                    String requestURI = request.getRequestURI();
                    basePath = StringUtils.replace(requestURL, requestURI, "");
                }
                basePath = basePath.substring(0,basePath.lastIndexOf("/elevator"))+"/";//basePath.replace("/elevator","");
                String zipPath = basePath + application.getPath();
                application.setPath(zipPath);
            }
        }
        else{
            return new Result(Result.FAILURE, "没有查询到最新程序!", null);
        }
        return new Result(Result.SUCCESS, Result.SUCCESS_MSG, applications);
    }
}